package com.demo.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 中文转拼音工具类
 */
public class PinyinUtils {

    /**
     * 获取中文的全拼（如 "张三" → "zhangsan"）
     */
    public static String getFullPinyin(String chinese) {
        if (chinese == null || chinese.trim().isEmpty()) {
            return "";
        }

        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder pinyin = new StringBuilder();
        char[] chars = chinese.toCharArray();

        for (char c : chars) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) { // 如果是中文
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        pinyin.append(pinyinArray[0]); // 取第一个拼音（多音字可能有多个）
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyin.append(c); // 非中文直接保留
            }
        }
        return pinyin.toString();
    }

    /**
     * 获取中文的首字母（如 "张三" → "zs"）
     */
    public static String getFirstLetters(String chinese) {
        if (chinese == null || chinese.trim().isEmpty()) {
            return "";
        }

        StringBuilder firstLetters = new StringBuilder();
        char[] chars = chinese.toCharArray();

        for (char c : chars) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) { // 如果是中文
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    firstLetters.append(pinyinArray[0].charAt(0)); // 取第一个拼音的首字母
                }
            } else {
                firstLetters.append(c); // 非中文直接保留
            }
        }
        return firstLetters.toString().toLowerCase();
    }
}